//
//  UIApplicationExt.swift
//  kano
//
//  Created by Frank on 2024/8/28.
//

import UIKit

extension UIApplication {
    var currentViewController: UIViewController? {
        guard let rootViewController = self.keyWindow?.rootViewController else {
            return nil
        }
        return getVisibleViewController(from: rootViewController)
    }
    
    private func getVisibleViewController(from vc: UIViewController) -> UIViewController {
        if let presentedVC = vc.presentedViewController {
            return getVisibleViewController(from: presentedVC)
        } else if let navigationController = vc as? UINavigationController {
            return getVisibleViewController(from: navigationController.visibleViewController ?? vc)
        } else if let tabBarController = vc as? UITabBarController {
            return getVisibleViewController(from: tabBarController.selectedViewController ?? vc)
        } else {
            return vc
        }
    }
}
